<?php
require_once APPPATH . "controllers/cmsbase.php";
define("DOWNLOAD_SEARCH","DOWNLOAD_SEARCH");
class cms_download extends CmsBase {

	var $_require_login = true;
	var $upload_config = null;

	function __construct() {
		parent :: __construct();
		// Check permission
		parent::_check_permission('pms_data');
		$this->load->model('Model_datagroup', 'model_datagroup');
		$this->load->model('Model_data', 'model_data');
	}

	/**
	 * Name: index
	 * Param: pagination param
	 * Description: Get list tbl_news_gr
	 *
	 */
	function index(){
		// Load pagination
		return $this->_render_my_view(array());
	}

	/**
	 *
	 *
	 */
	function browse_group(){
		$this->load->library('pagination');
		$groups = $this->model_datagroup->fetch_all();
		return $this->load->view("cms_download/browse_group", array("groups" => $groups));
	}

	/**
	 *
	 *
	 */
	function add_group()
	{
		if($_SERVER['REQUEST_METHOD'] === 'POST')
		{
			$data = parse_input('item_', $_POST);
			// Update group
			$id = $this->model_datagroup->insert_group($data);
			// redirect to browse
			$item = $this->model_datagroup->find($id);
			$result = array('status' => 'success', 'message' => '');
			echo json_encode($result);
			exit;
		}
		else{
			// Get max sort
			$max_sort = $this->model_datagroup->get_max_sort();
			$groups = $this->model_datagroup->fetch_all();
			// Load edit group view
			return $this->load->view("cms_download/add_group", array("groups" => $groups));
		}
	}

	/**
	 *
	 *
	 */
	function edit_group($id = 0){
		if($_SERVER['REQUEST_METHOD'] === 'POST')
		{
			$id = $this->input->post('id');
			if(intval($id)){
				$data = parse_input('item_', $_POST);
				// Update group
				$this->model_datagroup->update_group($data, $id);
				// redirect to browse
				$result = array('status' => 'success',
								'message' => '',
								'id'=>$_POST['id'] ,
								'item_description'=>$_POST['item_description'],
								'item_name'=>$_POST['item_name'],
								'item_sort'=>$_POST['item_sort']);
				echo json_encode($result);
				exit;
			}
		}
		else{
			// Load newsletter group
			if(intval($id)){
				$group = $this->model_datagroup->find($id);
				// Load edit group view
				return $this->load->view("cms_download/edit_group", array("group" => $group));
			}
		}
	}
	/**
	 *
	 *
	 */
	function delete_group($id){
		if(intval($id)){
			// get group id
			$this->model_datagroup->delete_group($id);
			// redirect to browse
			$result = array('status' => 'success', 'message' => '');
			echo json_encode($result);
		}
		exit;
	}


	/**
	 *
	 *
	 */
	function browse_document()
	{
		// Load pagination
		$this->load->library('pagination');

		$start = 0;
		$limit = 10;
		$search = null;
		$keyword = null;
		$fromdate = null;
		$todate = null;
		$group = null;
		$action = $this->input->post('actions');

		//print_r($_POST);exit;
		// if it dont post
		if($this->input->post('search')){
			$keyword = $this->input->post('keyword');
			$fromdate = $this->input->post('fromdate');
			$todate = $this->input->post('todate');
			$group = $this->input->post('group');
			$limit = $this->input->post('limit');
			if(!intval($limit)){
				$limit = 10;
			}

			// add to session
			$search = array('keyword' => $keyword,
							'fromdate' => $fromdate,
							'todate' => $todate,
							'group' => $group,
							'limit' => $limit);
			$_SESSION[DOWNLOAD_SEARCH] = $search;
		}
		elseif($action == 'delete'){

		}
		else{
			if(isset($_SESSION[DOWNLOAD_SEARCH])){
				$search = $_SESSION[DOWNLOAD_SEARCH];
				$keyword = $search['keyword'];
				$fromdate = $search['fromdate'];
				$todate = $search['todate'];
				$group = $search['group'];
				$limit = $search['limit'];
			}
		}

		$total = $this->model_data->browse_count($keyword, $group, $fromdate, $todate);
		$per_page = isset($_GET['per_page']) ? intval($_GET['per_page']):0;

		if($per_page){
			$start = $per_page;
		}

		$data = $this->model_data->browse($keyword, $group, $fromdate, $todate, $limit, $start);

		$config['base_url'] = site_url(array("c" => "cms_download", "m" => "browse_document"));
		$config['uri_segment'] = 3;
		$config['total_rows'] = $total;
		$config['per_page'] = $limit;
		$this->pagination->initialize($config);

		$groups = $this->model_datagroup->fetch_all();

		return $this->load->view("cms_download/browse_document", array("documents" => $data, 'search' => $search, 'groups' => $groups));
	}

	/**
	 *
	 *
	 */
	function add_document()
	{
		if($_SERVER['REQUEST_METHOD'] === 'POST')
		{
			$data = parse_input('item_', $_POST);
			// upload file
			$filename1 = $this->do_upload("fileupload1");
			if($filename1['success']){
				// update Newsletter
				$data['fullpath'] = $filename1['result']['full_path'];
				$data['filename'] = $filename1['result']['file_name'];
				$data['filetype'] = $filename1['result']['file_type'];
				$data['fileext']  = $filename1['result']['file_ext'];
				$data['size'] = $filename1['result']['file_size'];
				$this->model_data->insert_data($data);
				// redirect to browse
				$result = array('status' => 'success', 'message' => 'You have just insert new record');
			}
			else{
				$result = array('status' => 'failure', 'message' => $filename1['result']['error']);
			}
			echo json_encode($result);
			exit;
		}
		else{
			$groups = $this->model_datagroup->fetch_all();
			return $this->load->view("cms_download/add_document", array('groups' => $groups));
		}
	}

	/**
	 *
	 *
	 */
	function edit_document($id = 0)
	{
		if(intval($id)){
			if($_SERVER['REQUEST_METHOD'] === 'POST')
			{
				// update Newsletter
				$data = parse_input('document_', $_POST);
				// Check Upload file
				$result = array('status' => 'success',
								'message' => 'You have just update a record',
								'id' => $id,
								'document_name'=> $data['name'],
								'document_description'=> $data['description']
						);
				if(isset($_FILES['fileupload1']) and $_FILES['fileupload1']['tmp_name']){
					// delete file cu
					$document = $this->model_data->find($id);
					if(is_file($document['fullpath'])){
						unlink($document['fullpath']);
					}
					$filename1 = $this->do_upload("fileupload1");
					if($filename1['success']){
						// update Newsletter
						$data['fullpath'] = $filename1['result']['full_path'];
						$data['filename'] = $filename1['result']['file_name'];
						$data['filetype'] = $filename1['result']['file_type'];
						$data['fileext']  = $filename1['result']['file_ext'];
						$data['size'] = $filename1['result']['file_size'];
					}
					else{
						$result = array('status' => 'failure',
										'message' => $filename1['result']['error']);
					}
				}
				$this->model_data->update_data($data, $id);
				echo json_encode($result);
				exit;
			}
			else{
				$groups = $this->model_datagroup->fetch_all();
				$document = $this->model_data->find($id);
				return $this->load->view("cms_download/edit_document", array("document" => $document, 'groups' => $groups));
			}
		}
	}

	/**
	 *
	 *
	 */
	function delete_document()
	{
		// Delete file
		// get group id
		$id = $this->uri->segment(3,0);
		$this->model_data->delete_data($id);
		$query = $this->db->last_query();
		// redirect to browse
		$result = array('status' => 'success', 'message' => $query);
		echo json_encode($result);

	}

	function do_upload($field_name)
	{
		$path_download_file = $this->config->item('docs_upload_config');
		$config['upload_path'] = $path_download_file['upload_path'];
		$config['allowed_types'] = 'csv|pdf|doc|docx|xls|xlsx|swf|zip|txt|text|html|htm|gif|jpeg|jpg|png|bmp';
		$config['max_size']	= '4096';
		$config['max_width']  = '1024';
		$config['max_height']  = '768';

		$this->load->library('upload', $config);

		if ( ! $this->upload->do_upload($field_name))
		{
			$error = array('error' => $this->upload->display_errors());
			return array("success" => false, "result" => $error);
		}
		else
		{
			$data = array('upload_data' => $this->upload->data());
			return array("success" => true, "result" => $data['upload_data']);
		}
	}

	function get_newest_downloadgroup(){
		$result = $this->model_datagroup->find($this->model_datagroup->get_newest());
		$group = $result['id'];
		$count = $this->model_datagroup->count_all();
		$class = ($count%2) ? 'odd' : 'even';
		$str = "<tr class='$class' id='".$result['id']."'>";
		$str .= "<td class='small'><a class='ajax-edit' href='".site_url(array("c" => "cms_download", "m" => "edit_group", "id" => $group))."' alt='Edit''><img src='".image_url()."icons/edit.gif' alt='Edit'/></a></td>";
		$str .= "<td class='small'><a class='ajax-delete' href='".site_url(array("c" => "cms_download", "m" => "delete_group", "id" => $group))."' alt='Delete''><img src='".image_url()."icons/del.gif' alt='Delete'/></a></td>";
		$str .= "<td class='item_name'>".$result['name']."</td>";
		$str .= "<td class='item_description'>".$result['description']."</td>";
		$str .= "<td class='small'>".$result['quantity']."</td>";
		$str .= "<td class='small item_sort'>".$result['sort']."</td>";
		$str .= "</tr>";
		echo $str;
	}

	function get_newest_download(){
		$result = $this->model_data->find($this->model_data->get_newest());

		$group = $this->model_data->find($result['gid']);

		$count = $this->model_data->count_all();
		$class = ($count%2) ? 'odd' : 'even';
		$str = "<tr class='$class' id='".$result['id']."'>";
		$str .= "<td class='small'><input type='checkbox' class='newsletterId' name='newsletterIds[]' value='".$result['id']."'/></div>";
		$str .= "<td class='small'><a class='ajax-edit' href='".site_url(array("c" => "cms_download", "m" => "edit_document", "id" => $result['id']))."' alt='Edit''><img src='".image_url()."icons/edit.gif' alt='Edit'/></a></td>";
		$str .= "<td class='small'><a class='ajax-delete' href='".site_url(array("c" => "cms_download", "m" => "delete_document", "id" => $result['id']))."' alt='Delete''><img src='".image_url()."icons/del.gif' alt='Delete'/></a></td>";
		$str .= "<td class='item_name'>".$result['name']."</td>";
		$str .= "<td class='item_filetype'>".$result['filetype']."</td>";
		$str .= "<td class='item_size'><a class='dyna' href='#' title='".htmlspecialchars($result['description'])."'>".$result['size']."</td>";
		$str .= "<td class='small'>".$result['createddate']."</td>";
		$str .= "<td class='small item_sort'>".$result['sort']."</td>";
		$str .= "</tr>";
		echo $str;
	}
}
?>
